package com.example.lib.c2.pc4;

/**
 * 测试ThreadLocal
 * ThreadLocal保存的数据独立，不会相互影响
 */
public class TestThreadLoacal {

    static ThreadLocal<String> threadLocal = new ThreadLocal<String>(){
        @Override
        protected String initialValue() {
            return "西施";
        }
    };

    static class Thread1 extends Thread {
        @Override
        public void run() {
            super.run();
            System.out.println(Thread.currentThread().getName() + "-" + threadLocal.get());
            threadLocal.set("周杰伦");
            System.out.println(Thread.currentThread().getName() + "-" + threadLocal.get());
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            super.run();
            System.out.println(Thread.currentThread().getName() + "-" + threadLocal.get());
            threadLocal.set("张学友");
            System.out.println(Thread.currentThread().getName() + "-" + threadLocal.get());
        }
    }

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + "-" + threadLocal.get());
        threadLocal.set("猪八戒");
        System.out.println(Thread.currentThread().getName() + "-" + threadLocal.get());

        new Thread1().start();
        new Thread2().start();
    }
}
